/**
 * Copyright (C) 2011 Andrew C. Love (DNC) <dnc.app.sup@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dnc.cloak.framework.security.encryption;

import java.io.Serializable;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.log4j.Logger;

import com.dnc.cloak.framework.persistence.gen.Keystore;
import com.dnc.cloak.framework.security.X509Loader;


public class KeyContext extends Keystore implements Serializable{
	public enum KeyStoreSource { File, Database, Classpath};

	private static final Logger logger = Logger.getLogger(KeyContext.class.getName());

    private String keystoreName = "CloakKeystore";
    private String alias = "CloakKeystoreAlias";

	private String transformation;
	private String algorithm;
    private String providerClassName;
    private String encryptionMode;
    private String token;
    private String entryToken;
    private String location;
    
    private KeyStoreSource keytoreSource = KeyStoreSource.Database;    
    
    private byte[] privateKeyBytes;
    private byte[] publicKeyBytes;
    private byte[] symmetricKeyBytes;
    private byte[] certificateBytes;
    
    public KeyContext( ) {
        super();
    }
        
    public KeyStoreSource getKeystoreSource() {
		return keytoreSource;
	}

	public void setKeystoreSource(KeyStoreSource keyStoreSource) {
		this.keytoreSource = keyStoreSource;
	}

	public String getKeystoreName() {
        return keystoreName;
    }

    public void setKeystoreName(String keystoreName) {
        this.keystoreName = keystoreName;
    }

 	public PrivateKey getPrivateKey() {
        try {
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
            PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
            return privateKey;
        }
        catch (NoSuchAlgorithmException e) {
            logger.error(e);
        }
        catch (InvalidKeySpecException e) {
            logger.error(e);
        }
        return null;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public void setPrivateKey(PrivateKey privateKey) {
        this.privateKeyBytes = privateKey.getEncoded();
    }

    public PublicKey getPublicKey() {
        try {
            X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(publicKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
            PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
            return pubKey;
        }
        catch (NoSuchAlgorithmException e) {
            logger.error("Could not get Public Key-NoSuchAlgorithmException:" + algorithm, e);
        }
        catch (InvalidKeySpecException e) {
            logger.error("Could not get Public Key-InvalidKeySpecException", e);
        }
        return null;
    }

    public void setPublicKey(PublicKey publicKey) {
       this.publicKeyBytes = publicKey.getEncoded();
    }

    public void setSymmetricKey(SecretKey key) {
        this.symmetricKeyBytes = key.getEncoded();
    }

    public SecretKey getSymmetricKey() {        
        SecretKey secretKey = new SecretKeySpec(symmetricKeyBytes, algorithm);
        return secretKey;
    }

    public String getEncryptionMode() {
        return encryptionMode;
    }

    public void setAsymmetricEncryptionMode() {
        this.encryptionMode = EncryptionProperties.PKI;
    }

    public boolean isAsymmetricEncryptionMode() {
        return this.encryptionMode.equalsIgnoreCase(EncryptionProperties.PKI);
    }

    public void setSymmetricEncryptionMode() {
        this.encryptionMode = EncryptionProperties.SYM;
    }

    public boolean isSymmetricEncryptionMode() {
        return this.encryptionMode.equalsIgnoreCase(EncryptionProperties.SYM);
    }

    public void setSessionKeyEncryptionMode() {
        this.encryptionMode = EncryptionProperties.SESSION_KEY;
    }

    public boolean isSessionKeyEncryptionMode() {
        return this.encryptionMode.equalsIgnoreCase(EncryptionProperties.SESSION_KEY);
    }

    public Certificate getCertificate() {
        Certificate cert = null;
        byte[] buffer = certificateBytes;
        if (buffer != null && buffer.length > 0) {
            cert = X509Loader.getCertificate(buffer);
        }
        return cert;
    }

    public void setCertificate(Certificate certificate) {
        try {
            certificateBytes = certificate.getEncoded();
        }
        catch (CertificateEncodingException e) {
            logger.error("Could not set X.509 certificate", e);
        }
    }
  
    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getTransformation() {
        return transformation;
    }

    public void setTransformation(String transformation) {
        this.transformation = transformation;
    }

    public String getAlgorithm() {
        return algorithm;
    }

    public void setAlgorithm(String algorithm) {
        this.algorithm = algorithm;
    }

    public String getProviderClassName() {
        return providerClassName;
    }

    public void setProviderClassName(String providerClassName) {
        this.providerClassName = providerClassName;
    }
    
    public String getAlias() {
        return alias;
    }

    public void setAlias(String alias) {
        this.alias = alias;
    }   

    public String getEntryToken() {
        return entryToken;
    }

    public void setEntryToken(String entryToken) {
        this.entryToken = entryToken;
    }

    @Override
    public String toString() {
        return "KeyContext [transformation=" + transformation + ", algorithm="
                + algorithm + ", providerClassName="
                + providerClassName + ", alias="+ ", alias="
                + Arrays.toString(privateKeyBytes) + ", publicKeyBytes="
                + Arrays.toString(publicKeyBytes) + ", symmetricKeyBytes="
                + Arrays.toString(symmetricKeyBytes) + ", certificateBytes="
                + Arrays.toString(certificateBytes) + ", encryptionMode="
                + encryptionMode + ", keyStoreSource=" + keytoreSource
                + ", entryToken=" + entryToken + ", token=" + token + "]";
    }
    
}